package com.shopping.huaju.commodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.shopping.huaju.commodity.dao.CategoryBrandRelationDao;
import com.shopping.huaju.commodity.entity.CategoryBrandRelationEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.huaju.common.utils.PageUtils;
import com.shopping.huaju.common.utils.Query;

import com.shopping.huaju.commodity.dao.BrandDao;
import com.shopping.huaju.commodity.entity.BrandEntity;
import com.shopping.huaju.commodity.service.BrandService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {
    @Autowired
    private CategoryBrandRelationDao categoryBrandRelationDao;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Object obj = params.get("key");
        String key;
        if(obj != null){
            key = (String) obj;
        }else {
            key = "";
        }
        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                // 使用 QueryWrapper 对前端传入的 key 进行模糊查询
                new QueryWrapper<BrandEntity>().like("name",key)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateBrandAndRelation(BrandEntity brand) {
        this.updateById(brand);
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setBrandName(brand.getName());
        categoryBrandRelationEntity.setBrandId(brand.getId());
        categoryBrandRelationDao.update(categoryBrandRelationEntity,
                new UpdateWrapper<CategoryBrandRelationEntity>().eq("brand_id",brand.getId()));
    }

    @Override
    @Transactional
    /* 删除品牌的同时，删除与该品牌关联的数据*/
    public void deleteBrandAndRelation(Long[] ids) {
        this.removeByIds(Arrays.asList(ids));
        categoryBrandRelationDao.delete(new QueryWrapper<CategoryBrandRelationEntity>()
                .in("brand_id",Arrays.asList(ids)));
    }

}